package com.vimhe.liteftpserver;

import com.vimhe.ftpserver.spring.boot.autoconfigure.ext.FtpUserManager;
import lombok.RequiredArgsConstructor;
import org.apache.ftpserver.ftplet.UserManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.reactive.config.ResourceHandlerRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import java.io.File;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * Webflux 配置
 *
 * @author Vimhe
 */
@RequiredArgsConstructor
@Configuration
public class LiteFtpServerConfig implements WebFluxConfigurer {

    private final UserManager userManager;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        Arrays.stream(((FtpUserManager) userManager).getAllUser())
            .forEach(user -> {
                String url = user.getHomeDirectory();
                url = url.endsWith(File.separator) ? url : url + File.separator;

                registry.addResourceHandler("/" + user.getName() + "/**")
                    .addResourceLocations("file://" + url)
                    .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
            });
    }

}
